//
//  ZMUserAccountModel.swift
//  ZMWeiboSwift
//
//  Created by pg on 2017/7/25.
//  Copyright © 2017年 pg. All rights reserved.
//

import UIKit
//用户模型信息保存在本地沙盒中的地址
let userAccountPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archive")

class ZMUserAccountModel: NSObject , NSCoding {
    //微博 访问令牌
    var access_token : String?
    //访问令牌的过期秒数
    var expires_in : Int = 0 {
        didSet{
            //过期时间 = 当前时间+过期秒数
            expiresDate = Date().addingTimeInterval(TimeInterval(expires_in))
        }
    }
    //计算属性, 根据秒数,获取过期时间对象
    var expiresDate:Date?
    //用户id
    var uid : Int64 = 0
    //用户名
    var name : String?
    //用户头像 网络地址
    var avatar_large : String?
    
        init(dic: [String : Any]) {
        super.init()
        setValuesForKeys(dic)
        
        
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
    //MARK:- 归档
    func encode(with aCoder: NSCoder) {
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expiresDate, forKey: "expiresDate")
        
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
        
    }
    //解档
    required init?(coder aDecoder: NSCoder) {
       access_token = aDecoder.decodeObject(forKey: "access_token") as? String
       expiresDate = aDecoder.decodeObject(forKey: "expiresDate") as? Date
       uid = aDecoder.decodeInt64(forKey: "uid")
       name = aDecoder.decodeObject(forKey: "name") as? String
       avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
        
    }
    
    //保存用户对象
    func saveUserAccount(){
      //  let userAccountPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archive")
        NSKeyedArchiver.archiveRootObject(self, toFile: userAccountPath)
    }
    
    
    //读取用户对象
    class func loaduserAccountModel()->(ZMUserAccountModel?){
        let userAccount = NSKeyedUnarchiver.unarchiveObject(withFile: userAccountPath) as? ZMUserAccountModel
        
        return userAccount
    }
    
//    func test() -> Void {
//        var count: UInt32 = 0
//        var ivarlist = class_copyIvarList(self.classForCoder,&count)
//        
//    
//
//    }
    
}
